﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace KyFileSyncTransfer.Business
{
    /// <summary>
    /// WEB API接口调用类
    /// 作者：左文俊
    /// 日期：2016-08-19
    /// </summary>
    public static class WebApiUtility
    {
        public static async Task<JObject> HttpPost(Dictionary<string, string> requestHeaders, Dictionary<string, object> requestData, string serviceUrl)
        {
            string dataStr = JsonConvert.SerializeObject(requestData);
            var content = new StringContent(dataStr, Encoding.UTF8, "application/json");
            if (requestHeaders != null)
            {
                foreach (var item in requestHeaders)
                {
                    content.Headers.Add(item.Key, item.Value);
                }
            }
            HttpClient httpClient = new HttpClient();
            var result = await httpClient.PostAsync(serviceUrl, content);
            result.EnsureSuccessStatusCode();
            return JObject.Parse(await result.Content.ReadAsStringAsync());
        }

        public static async Task<JObject> HttpGet(Dictionary<string, string> requestHeaders, Dictionary<string, object> requestData, string serviceUrl)
        {

            HttpClient httpClient = new HttpClient();

            if (requestHeaders != null)
            {
                foreach (var item in requestHeaders)
                {
                    httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }

            string dataStr = null;
            if (requestData != null)
            {
                foreach (var item in requestData)
                {
                    dataStr += string.Format("&{0}={1}", item.Key, UrlEncode(item.Value.ToString()));
                }
                serviceUrl += serviceUrl.Contains("?") ? dataStr : "?" + dataStr.Substring(1);
            }

            var result = await httpClient.GetAsync(serviceUrl);
            result.EnsureSuccessStatusCode();
            return JObject.Parse(await result.Content.ReadAsStringAsync());
        }

        public static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str);
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }
            return (sb.ToString());
        }
    }
}
